
<style> 
#efence_list{ position:absolute; left:0px; top:0px; background:#FFFFFF; width:400px;height:100% }
#efence_tool { position:absolute; left:420px; top:10px; background:#FFFFFF; width:65%;}
</style> 

<div id="map_box" class ="baidu-maps" style="width: 100%;height: 100%"></div>
  <div id="efence_list" class="layui-coutainer">
    <!-- 隐藏设备栏 -->
    <i style="position: absolute;right: 0" class="layui-icon layui-icon-close" onclick="dev_panle_sw('hide')"></i>
    <!-- 路线列表开始 -->
    <form class="layui-form layui-form-pane" action="" style="width:auto;height: 15px;padding: 5px;">
      <div class="layui-form-item">
          <div class="layui-inline" >
              <div class="layui-input-inline" style="width: 280px">
                  <input type="text"  name="search_key"  placeholder="输入路线名称,查找路线详情" autocomplete="off" class="layui-input" style="height: 30px;">
              </div>
              <div class="layui-form-mid layui-word-aux"></div>
              <a type="button" class="layui-btn layui-btn-sm" lay-submit="" lay-filter="data-search-btn" >搜索</a>
          </div>
      </div>
    </form>
  <table id="efence_list_table" class="layui-table" lay-filter="efence_list_table"></table>
  <!-- 路线列表结束 -->
  <!-- 单个设备绑定的路线列表开始 -->
  <form class="layui-form layui-form-pane" action="" style="width:auto;height: 15px;padding: 5px;">
    <div class="layui-form-item">
        <div class="layui-inline" >
            <div class="layui-input-inline" style="width: 280px">
                <input type="text"  name="search_key"  placeholder="输入设备名称/ID,查找设备绑定路线" autocomplete="off" class="layui-input" style="height: 30px">
            </div>
            <div class="layui-form-mid layui-word-aux"></div>
            <a type="button" class="layui-btn layui-btn-sm" lay-submit="" lay-filter="dev-efe-search-btn" >搜索</a>
        </div>
    </div>
  </form>
  <table id="efence_of_dev_table" class="layui-table" lay-filter="efence_of_dev_table"></table>
  <!-- 单个设备绑定的路线列表结束 -->
</div>
<!-- 设备栏展示按钮 -->
<button id="show_sw" class="layui-btn" onclick="dev_panle_sw('show')" style="position: absolute;left:-20px;top: 40%;height: 150px;width: 10px;display: none;"><i class="layui-icon">&#xe66b;</i></button>
<script type="text/html" id="draw_efence">
    <a class="layui-btn layui-btn-sm" lay-event="draw_efence" style="display: none;">新建</a>
</script>

<!-- 工具栏 -->
<div  id="efence_tool" style="color:white;background-color:rgba(320,138,138,0)">
  <div class="layui-inline" >
     <div class="layui-input-inline">
        <button class="layui-btn layui-btn-sm" onclick="reset_efence()">重置路线</button>
     </div>
  </div>
  <div class="layui-inline" >
      <div class="layui-input-inline">
          <input type="text"  id="search_address"  placeholder="搜索地址" autocomplete="off" class="layui-input" style="height: 30px">
      </div>
      <div class="layui-form-mid layui-word-aux"></div>
      <a type="button" class="layui-btn layui-btn-sm" onclick="search_map($('#search_address').val())">搜索</a>
  </div>
  <div class="layui-inline" >
     <div class="layui-input-inline">
        <button class="layui-btn layui-btn-sm" onclick="select_draw_kind('nav')" >设置导航路线</button>
     </div>
  </div>
  <div class="layui-inline" >
     <div class="layui-input-inline">
        <button class="layui-btn layui-btn-sm" onclick="select_draw_kind('trail')">导入历史轨迹路线</button>
     </div>
  </div>
  <div class="layui-inline" >
     <div class="layui-input-inline">
        <button class="layui-btn layui-btn-sm" onclick="select_draw_kind('manual')">手工绘制路线</button>
     </div>
  </div>
  
</div>

<!-- 查询导航路劲为路线start -->
<form class="layui-form layui-form-pane " action="" id="nav_query_form" lay-filter="nav_query_form" style="display: none;padding: 10px">
  <div class="layui-form-item" style="color:black">
    <div class="layui-inline">
      <label class="layui-form-label layui-bg-green">起点</label>
      <div class="layui-input-inline" >
          <input type="text"  name="s_address" lay-verify="required"  placeholder="起点" autocomplete="off" class="layui-input">
      </div>
    </div>
    <div class="layui-inline">
      <label class="layui-form-label layui-bg-green">终点</label>
      <div class="layui-input-inline" >
          <input type="text"  name="e_address" lay-verify="required"   placeholder="终点" autocomplete="off" class="layui-input">
      </div>
    </div>
  </div>
  <div class="layui-form-item" style="color:black">
    <div class="layui-inline">
      <label class="layui-form-label layui-bg-green">路线总长</label>
      <div class="layui-input-inline" >
          <input type="text"  name="total_distance"  placeholder="路线总长，单位（米）" autocomplete="off" class="layui-input">
      </div>
    </div>
  </div>
  <div class="layui-row" style="color:black">
    <div class="layui-col-md6">
      <button class="layui-btn " lay-submit lay-filter="nav_query" style="width: 90%"><i class="layui-icon layui-icon-search" ></i>查询</button>
    </div>
    <div class="layui-col-md6">
      <button class="layui-btn" lay-submit lay-filter="line_upload" style="width: 90%">设置路线</button>
    </div>
  </div>
  
</form>
<!-- 查询导航路劲为路线end -->

<!-- 历史轨迹查询，导入历史轨迹作为路线start -->
<form class="layui-form layui-form-pane " action="" id="trail_query_form" lay-filter="trail_query_form" style="display: none;padding: 10px">
  <div class="layui-form-item" style="color:black">
    <div class="layui-inline">
      <label class="layui-form-label layui-bg-green">开始时间</label>
      <div class="layui-input-inline">
        <input type="text" id="s_trail" name="s_time" lay-verify="required"  autocomplete="off" class="layui-input">
      </div>
    </div>
    <div class="layui-inline">
      <label class="layui-form-label layui-bg-green">结束时间</label>
      <div class="layui-input-inline">
        <input type="text" id="e_trail" name="e_time" lay-verify="required"  autocomplete="off" class="layui-input">
      </div>
    </div>
    <div class="layui-inline">
      <label class="layui-form-label layui-bg-green">轨迹类型</label>
      <div class="layui-input-inline" >
        <select name="trail_filter" placeholder="轨迹过滤" >
          <option value="satelite">BDS/GPS</option>
          <option value="wifi">WIFI</option>
          <option value="lbs">LBS</option>
        </select>
      </div>
    </div>
    <div class="layui-inline">
      <label class="layui-form-label layui-bg-green">设备选择</label>
      <div class="layui-input-inline" >
        <select id="tml_list" name="device_id"  lay-verify="required" lay-search="" class="layui-input" placeholder="" >
        </select>
      </div>
    </div>
  </div>
  
  <div class="layui-row" style="color:black">
    <div class="layui-col-md6">
      <button class="layui-btn " lay-submit lay-filter="trail_query" style="width: 90%"><i class="layui-icon layui-icon-search" ></i>查询</button>
    </div>
    <div class="layui-col-md6">
      <button class="layui-btn" lay-submit lay-filter="line_upload" style="width: 90%">设置路线</button>
    </div>
  </div>
  
</form>
<!-- 历史轨迹查询，导入历史轨迹作为路线end -->


<!-- 手工绘制路线start -->
<form class="layui-form layui-form-pane " action="" id="manual_draw_form" lay-filter="manual_draw_form" style="display: none;padding: 10px">
  <div class="layui-form-item" style="color:black">
    <div class="layui-inline">
      <label class="layui-form-label layui-bg-green">起点</label>
      <div class="layui-input-inline" >
          <input type="text"  name="s_address" lay-verify="required"  placeholder="起点" autocomplete="off" class="layui-input">
      </div>
    </div>
    <div class="layui-inline">
      <label class="layui-form-label layui-bg-green">终点</label>
      <div class="layui-input-inline" >
          <input type="text"  name="e_address" lay-verify="required"   placeholder="终点" autocomplete="off" class="layui-input">
      </div>
    </div>
  </div>
  <div class="layui-form-item" style="color:black">
    <div class="layui-inline">
      <label class="layui-form-label layui-bg-green">路线总长</label>
      <div class="layui-input-inline" >
          <input type="text"  name="total_distance"  placeholder="路线总长，单位（米）" autocomplete="off" class="layui-input">
      </div>
    </div>
  </div>

  <button class="layui-btn layui-btn-fluid" lay-submit lay-filter="line_upload" lay-event='manual' style="width: 90%">提交路线</button>

</form>
<!-- 查询导航路劲为路线end -->

<!-- 路线设置表格开始 -->

<form  class="layui-form layui-form-pane " id="handle_data_form" action=""  lay-filter="handle_data_form" style="display: none;padding: 10px">
    <div class="layui-form-item">
      <div class="layui-inline">
        <label class="layui-form-label layui-bg-green">路线名称</label>
        <div class="layui-input-block">
          <input id="efe_name" type="text" name="name" lay-verify="required" lay-reqtext="必填项!" placeholder="不可重复" autocomplete="off" class="layui-input">
        </div>
      </div>
    </div>
    <div class="layui-form-item">
      <div class="layui-inline">
        <label class="layui-form-label layui-bg-green">生效时间</label>
        <div class="layui-input-inline">
          <input id="s_time"  type="text" name="s_time" lay-verify="required"  placeholder="开始时间" autocomplete="off" class="layui-input">
        </div>
      </div>
      <div class="layui-inline">
        <label class="layui-form-label layui-bg-green">结束时间</label>
        <div class="layui-input-inline">
          <input id="e_time"  type="text" name="e_time" lay-verify="required"  placeholder="结束时间" autocomplete="off" class="layui-input">
        </div>
      </div>
    </div>

    <div class="layui-form-item">
      <div class="layui-inline">
        <label class="layui-form-label layui-bg-green">使用频率</label>
        <div class="layui-input-inline">
          <input id="effect_time" type="phone" name="effect_time"  placeholder="" autocomplete="off" class="layui-input alarm_clock">
        </div>
        <div class="layui-input-inline" style="width: 100px" >
          <select name="effect_rate" lay-filter="effect_rate">
            <option value="1111111">每天</option>
            <option value="1111100">周一周五</option>
            <option value="customize">自定义</option>
          </select>
        </div>
        <div class="layui-input-inline customize" style="display: none;" >
          <select name="customize" xm-select="customize" xm-select-type="1" xm-select-height="36px">
            <option value="1">星期一</option>
            <option value="2">星期二</option>
            <option value="3">星期三</option>
            <option value="4">星期四</option>
            <option value="5">星期五</option>
            <option value="6">星期六</option>
            <option value="7">星期日</option>
          </select>
        </div>
      </div>
    </div>

    <div class="layui-form-item" style="display: none;">
      <div class="layui-inline">
        <label class="layui-form-label layui-bg-green">偏移范围</label>
        <div class="layui-input-inline">
          <input type="text" name="alarm_kind" value="20" placeholder="" autocomplete="off" class="layui-input">
        </div>
        <div class="layui-form-mid layui-word-aux">米</div>
      </div>
    </div>
    <div class="layui-form-item" style="display: none;">
      <div class="layui-inline">
        <label class="layui-form-label layui-bg-green">路线类型</label>
        <div class="layui-input-inline">
          <input type="text" name="kind"  autocomplete="off" class="layui-input">
        </div>
      </div>
      <div class="layui-inline">
        <label class="layui-form-label layui-bg-green">路线内容</label>
        <div class="layui-input-inline">
          <input type="text" name="content" autocomplete="off" class="layui-input">
        </div>
      </div>
    </div>
  <div id="efence_bind_dev" class="layui-transfer" style="padding: 10px"></div>
</form>

<!-- 路线设置表格结束 -->

<!-- 百度地图的相关调用，定位打点，地址解析等 -->
<script type="text/javascript" src="/static/js/bd_map.js"></script>

<script type="text/html" id="currentTableBar">
    <a class="layui-btn layui-btn-xs " lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>

<script type="text/javascript">

$('.layui-body').attr('style','padding:0px;bottom:0px;left:0') 

var dev_panle_sw=function(command){
  if(command=='hide'){
    $('#efence_list').hide()
    $('#show_sw').show()
  }else{
    $('#efence_list').show()
    $('#show_sw').hide()
  } 
}

form.render()
formSelects.render()

// 使用频率自定义项目隐藏与展示
form.on('select(effect_rate)',function(obj){

  if(obj.value=='customize'){
    $('.customize').show()
  }else{
    $('.customize').hide()
  }
})

// 填充地图选择下拉框
// var map_obj_list={}
// for(var i=0;i<all_map_data.length;i++){
//   var map_obj=all_map_data[i]
//   var map_name=map_obj.name
//   map_obj_list[map_name]=map_obj
//   var opt='<option value="'+map_name+'">'+map_name+'</option>'
//   $('#map_filter_list').append(opt)
// }

// // 监听地图切换
// var chose_map=function(obj){
//   console.log('ok',obj.value,obj)
//   var page_name='polyline'
//   if(obj.value!=='bd'){
//     map_to_show=map_obj_list[obj.value]
//     layui.data('map_to_show',{key:'map_to_show',value:JSON.stringify(map_to_show)})
//     page_name=map_to_show.content.split('.')[1]+'_polyline'
//   }
//   window.history.pushState(null, null, "/index/#"+page_name)
//   turn_to_page(page_name)
// }

var ajax_url='polyline';
// 获取路线数据，加载到路线表格
var efence_info;

var efence_table=function(data){
  efence_info=data
  table.render({
    elem: '#efence_list_table',
    data: data,
    toolbar:'#draw_efence',
    id:'efence_list_table',
    skin:'nob',
    size:'sm',
    height: (get_height-60)/2-20,
    cols: [[
        {type: "checkbox", fixed: "left"},
        {field: 'name', title: '名称',sort:true},
        // {field: 'alarm_kind', title: '偏移范围',sort:true},
          {field: 'device_id', title: '绑定设备',sort:true},
          {title: '操作', minWidth: 110, templet: '#currentTableBar', fixed: "right", align: "center"}

          ]],
    // page: true,
    limit:100
  });

}

get_info_ajax(ajax_url,'get_init_data&map_kind=bd',efence_table)

// 标注已经绑定路线的设备，原则上，一个设备只能绑定一条路线
for(var i=0;i<device.length;i++){
  if(device[i].polyline!=='0'){
    device[i].disabled=true
  }
}

// 重置路线
var reset_efence=function(){
    map.clearOverlays()
    map.removeEventListener('click',manual_draw_line);
    all_point=[]
    line_dis=0
    draw_line_kind=null

}


// 路线点击事件
var efence_click=function(efence_self){
  var efe_detail;
  var efe_name=efence_self.target.name
  document.getElementById("handle_data_form").reset();

  for(var i=0;i<efence_info.length;i++){
    if(efence_info[i]['name']==efe_name){
      efe_detail=efence_info[i]
    }
  }
  var p_dev=eval(efe_detail['device_id'])

  form.val('handle_data_form',efe_detail)

  transfer.reload('binded_dev', {
                  data: device
                  ,value: p_dev
                  ,title: ['未绑定', '绑定']
                  ,height:320
                  ,width:280
                  ,showSearch: true
                  ,parseData: function(res){

                    return {
                      "value": res.device_id //数据值
                      ,"title": '名称：'+res.user_name+'    ID:'+ res.device_id //数据标题
                      ,"disabled":res.disabled  //是否禁用
                      ,"checked": '' //是否选中
                    }
                  }
  })

  layer.open({
              type: 1
              ,title:'路线详情'
              ,area:['700px','650px']
              ,offset:'60px'  
              ,id: 'efe_data_form' //防止重复弹出
              ,content:$('#handle_data_form')
              ,shade: 0 //不显示遮罩

            });

}



// 监听编辑按钮
table.on('tool(efence_list_table)',function(obj){
  $('#efe_name').attr('readonly','readonly')
  console.log(obj)
  var efe_detail=obj.data;
  if (obj.event=='del'){
    layer.confirm("确定删除路线："+efe_detail.name+"？",
              {btn: ['是', '否']}, 
              function (index) {
                post_info_ajax(efe_detail,ajax_url,'del&map_kind=bd',efence_table)
              }
              ,function(){
                console.log('no')
                layer.closeAll()
              });
    return
  }

  // 使用频率转化
  var alarm_kind=eval('('+efe_detail['alarm_kind']+')')
  var effect_rate=alarm_kind['effect_rate']
  var effect_time=alarm_kind['effect_time']
  if (effect_rate!=='1111111' && effect_rate!=='1111100'){
    effect_rate=effect_rate.split('')
    var res=[]
    for(var i=0;i<effect_rate.length;i++){
      if((effect_rate[i])=='1'){
        res.push(JSON.stringify(i+1))
      }
    }
    // res=res.join(',')
    formSelects.value('customize', res)
    effect_rate='customize'
    $('.customize').show()
  }else{
    $('.customize').hide()
  }
  efe_detail['effect_rate']=effect_rate

  if(effect_time!=''){
    effect_time=effect_time[0]+' - '+effect_time[1]
  }
  efe_detail['effect_time']=effect_time

  // 给表格赋值
  document.getElementById("handle_data_form").reset();
  form.val('handle_data_form',efe_detail)

  var org_bin_dev=eval(efe_detail['device_id'])
  transfer.reload('binded_dev', {
                  data: device
                  ,value:org_bin_dev
                  ,title: ['未绑定', '绑定']
                  ,height:320
                  ,width:280
                  ,showSearch: true
                  ,parseData: function(res){
                    if(res.polyline!='0'){
                      var name=eval('('+res.polyline+')').name
                      if(name==efe_detail.name){
                        res.disabled=false
                      }
                    }
                    return {
                      "value": res.device_id //数据值
                      ,"title": '名称：'+res.user_name+'    ID:'+ res.device_id //数据标题
                      ,"disabled":res.disabled  //是否禁用
                      ,"checked": '' //是否选中
                    }
                  }
  })
  layer.open({
              type: 1
              ,title:'路线设置'
              ,area:['700px','650px']
              ,offset:'60px'  
              ,closeBtn:0
              ,id: 'efe_data_form' //防止重复弹出
              ,content:$('#handle_data_form')
              ,btn: ['提交','关闭']
              ,shade: 0 //不显示遮罩
              ,btn1: function(){
                var base_info=form.val('handle_data_form')
                base_info['content']=eval(efe_detail.content)
                base_info=package_data(base_info)
                console.log(base_info)
                post_info_ajax(base_info,ajax_url,'edit&map_kind=bd')
              }
              ,btn2: function(){
                layer.closeAll();
                reset_efence()
              }
            });
})

// 点击路线列表，显示路线内容
var checkDiv=new Array();
// 监听设备列表点击
table.on('row(efence_list_table)', function(obj){
 //选中行同步选中复选按钮
    var tr = obj.tr;
    var div = tr.find("div.layui-unselect");
    //checkDiv为定义的属性用来缓存当前点击的行是否选中状态，未选择的选中，选中的取消选中，并进行相应的地图打点处理
    // console.log(obj.data.device_id)
    if(!checkDiv[obj.data.name]) {
      checkDiv[obj.data.name] = obj;
      div.addClass("layui-form-checked");
      efence_show(obj.data)

    } else {
      div.removeClass("layui-form-checked");
      delete checkDiv[obj.data.name];
      efence_remove(obj.data.name)

    }

});

// 地图上展示路线
var s_marker_obj={},e_marker_obj={},line_obj={};
var efence_show=function(row){
  var efencepath=row.content;
  efencepath=eval(efencepath);

  var polyline_points=new Array();
  for(var i=0;i<efencepath.length;i++){
    var p_p=new BMap.Point(efencepath[i][0],efencepath[i][1])
    polyline_points.push(p_p);

  }
  map.setViewport(polyline_points);
  var efence_done=new BMap.Polyline(polyline_points)
  efence_done.name=row.name
  line_obj[row.name]=efence_done
  map.addOverlay(efence_done);
  // 添加点击事件
  efence_done.addEventListener("click",efence_click);
  var s_icon=new BMap.Icon("/static/img/start.png", new BMap.Size(50,50),{anchor : new BMap.Size(20, 42),imageSize:new BMap.Size(50,50)});
  var e_icon=new BMap.Icon("/static/img/end.png", new BMap.Size(50,50),{anchor : new BMap.Size(20, 42),imageSize:new BMap.Size(50,50)});
  s_marker = new BMap.Marker(polyline_points[0],{icon:s_icon});
  e_marker= new BMap.Marker(polyline_points[polyline_points.length-1],{icon:e_icon});
  s_marker_obj[row.name]=s_marker
  e_marker_obj[row.name]=e_marker
  map.addOverlay(s_marker);
  map.addOverlay(e_marker);
}


//删除地图上面显示的指定路线
var efence_remove=function(efence_name){
  // console.log(s_marker_obj,s_marker_obj[efence_name],efence_name)
  if(s_marker_obj[efence_name]!=null){
    map.removeOverlay(s_marker_obj[efence_name])
  }
  if(e_marker_obj[efence_name]!=null){
    map.removeOverlay(e_marker_obj[efence_name])
  }
  if(line_obj[efence_name]!=null){
    map.removeOverlay(line_obj[efence_name])
  }
  // var fugaiwu = map.getOverlays();
  // for(var i=0,n=fugaiwu.length;i<n;i++){
  //   if (fugaiwu[i].name==efence_name) {
  //     map.removeOverlay(fugaiwu[i]); 
  //     return false;
  //   };
  // };
};


// 监听路线搜索操作
form.on('submit(data-search-btn)', function (data) {

  var search_key = data.field['search_key'];
  if(search_key!==''){
    // 调用index页面搜索函数
    var search_result=search_func(efence_info,search_key,'name','kind')
    // 表格重载
    efence_table(search_result)
  }else{
    efence_table(efence_info)
  }
  return false;
});

// 监听指定设备的路线搜索操作
form.on('submit(dev-efe-search-btn)', function (data) {

  var search_key = data.field['search_key'];
  if(search_key!==''){
    // 调用index页面搜索函数
    var search_result=search_func(device,search_key,'device_id','user_name')
    // 表格重载
    console.log(search_result)
    if(search_result[0]['polyline']=='0'){
      efence_of_dev_table([])
    }else{
      search_result=eval('('+search_result[0]['polyline']+')')
      efence_of_dev_table([search_result])
    }

    }else{
      efence_of_dev_table([])
    }
    return false;
});

// 根据设备id，查找设备绑定的路线详情
var efence_of_dev_table=function(data){
table.render({
  elem: '#efence_of_dev_table',
  data: data,
  // toolbar:'#draw_efence',
  id:'efence_of_dev_table',
  skin:'nob',
  size:'sm',
  height: (get_height-60)/3,
  cols: [[
      {type: "checkbox", fixed: "left"},
      {field: 'name', title: '名称',sort:true},
      // {field: 'alarm_kind', title: '偏移范围',sort:true},
      {field: 'time', title: '生效时间',sort:true,
        templet: function(d){
          var effect_time=d.s_time+'--'+d.e_time
          return effect_time
        }
      }
        // {title: '操作', minWidth: 110, templet: '#currentTableBar', fixed: "right", align: "center"}

        ]],
  // page: true,
  limit:100
});

}
efence_of_dev_table([])

// 点击路线列表，显示路线内容
var checkefe=new Array();
// 监听设备列表点击
table.on('row(efence_of_dev_table)', function(obj){
 //选中行同步选中复选按钮
    var tr = obj.tr;
    var div = tr.find("div.layui-unselect");
    //checkDiv为定义的属性用来缓存当前点击的行是否选中状态，未选择的选中，选中的取消选中，并进行相应的地图打点处理
    // console.log(obj.data.device_id)
    if(!checkefe[obj.data.name]) {
      checkefe[obj.data.name] = obj;
      div.addClass("layui-form-checked");
      efence_show(obj.data)

    } else {
      div.removeClass("layui-form-checked");
      delete checkefe[obj.data.name];
      efence_remove(obj.data.name)

    }

});

// 百度地图地址搜索功能
var local = new BMap.LocalSearch(map, {
    renderOptions:{map: map}
  });
var search_map=function(addr){
  console.log(addr)
  local.search(addr);
}




// 路线设置面板，输入参数和提交后台
var add_polyline_set=function(){
  
    layer.confirm("是否绘制完毕？",
                {btn: ['是', '重绘']}, 
                function (index) {
                                  layer.closeAll('dialog');
                                  $('#efe_name').removeAttr('readonly')
                                  layer.open({
                                    type: 1
                                    ,title:'路线设置'
                                    ,area:['700px','650px']
                                    ,offset:'60px'  
                                    ,closeBtn:0
                                    ,id: 'efe_data_form' //防止重复弹出
                                    ,content:$('#handle_data_form')
                                    ,btn: ['提交','关闭']
                                    ,shade: 0 //不显示遮罩
                                    ,btn1: function(){
                                      var base_info=form.val('handle_data_form')
                                      if(base_info['name']==''){
                                        layer.msg('请输入路线名称')
                                        return false
                                      }
                                      
                                      var polyline=eval(base_info['content'])
                                      // 路线点细化，两个点的距离不超过200米
                                      var wait_for_ready = layer.load(1);
                                      polyline=get_point_of_polyline(polyline,200)
                                      layer.close(wait_for_ready); 
                                      // draw_line_bdmap(polyline)
                                      base_info['content']=polyline
                                      base_info=package_data(base_info)
                                      console.log(base_info)
                                      post_info_ajax(base_info,ajax_url,'add&map_kind=bd',efence_table)
                                    }
                                    ,btn2: function(){
                                      layer.closeAll();
                                      reset_efence()
                                    }
                                  });

                                }, function(){
                                  reset_efence()
                                });
}


// 封装与后台交互的数据
var package_data=function(result){

  var binded_dev=transfer.getData('binded_dev');
  result['device_id']=[]
  for(var i=0;i<binded_dev.length;i++){
    result['device_id'].push(binded_dev[i]['value'])
  }
  var effect_rate=result['effect_rate']
  if(effect_rate=='customize'){
    var customize=result['customize'].split(',')
    var res='0000000'.split('')
    for(var i=0;i<customize.length;i++){
      res[parseInt(customize[i])-1]='1'
    }
    effect_rate=res.join('')
  }
  var effect_time=result['effect_time']
  if(effect_time!=''){
    effect_time=effect_time.split(' ')
    effect_time=[effect_time[0],effect_time[2]]
  }
  var alarm_kind={'effect_rate':effect_rate,'effect_time':effect_time}
  result['alarm_kind']=alarm_kind
  result['kind']='polyline'

  delete result['customize']
  delete result['effect_rate']
  delete result['effect_time']

  return result
}

// 路线设置提交
form.on('submit(line_upload)',function(obj){

  var line=form.val('handle_data_form')
  console.log(line)
  if(line.content==''){
    layer.msg('请先绘制路线')
    return false
  }
  layer.closeAll()
  add_polyline_set()
  return false
})


//导航路线数据提取
var get_nav_point=function(pois){
  //map.clearOverlays()
  console.log(pois)
  var all_p=new Array();
  var total_distance=0;
  for(var n=0;n<pois.length;n++){
    var ef_p=pois[n].getPath();
    // console.log(pois[n].cg)
    total_distance=total_distance+pois[n].cg
    all_p=all_p.concat(ef_p)
  }
  console.log(all_p,total_distance/1000)
  form.val('nav_query_form',{'total_distance':total_distance+'米'})
  form.val('handle_data_form',{'content':JSON.stringify(all_p),'kind':'polyline'})
};

//导航路线查找
var search_polyline=function(){
  var transit = new BMap.DrivingRoute(map, {
    renderOptions: {
      map:map,
      enableDragging :true //起终点可进行拖拽
    },  
    onPolylinesSet:get_nav_point,
    // onSearchComplete:nav_result
  });
  var s_address=$('#s_address').val(),e_address=$('#e_address').val();
  setTimeout(function(){transit.search(s_address,e_address);},200)
}


//手工路线绘制，把路线的点集合赋值给content
var all_point=[]
var line_dis=0
var manual_draw_line = function(point){
  console.log(point.point)
  all_point.push(point.point)
  // 地图打点
  var p_icon = new BMap.Icon("/static/img/point.png", new BMap.Size(5,5),{imageSize:new BMap.Size(5, 5)});
  var m = new BMap.Marker(point.point,{icon:p_icon});
  map.addOverlay(m); 
  
  // 画线
  if(all_point.length>1){
    var pts=[all_point[all_point.length-2],all_point[all_point.length-1]]
    var polyline = new BMap.Polyline(pts, {
      strokeColor:"red",//设置颜色
      strokeWeight:2 ,//宽度
      strokeOpacity:0.8,//折线的透明度，取值范围0 - 1
      enableClicking: false,//是否响应点击事件，默认为true
      // icons:[icons]
    });
    map.addOverlay(polyline);
    // 计算距离
    var d=map.getDistance(all_point[all_point.length-2],all_point[all_point.length-1])
    line_dis=line_dis+d
    form.val('manual_draw_form',{'e_address':point.point.lng+','+point.point.lat})
    form.val('manual_draw_form',{'total_distance':line_dis.toFixed()+'米'})
    form.val('handle_data_form',{'content':JSON.stringify(all_point),'kind':'polyline'})
  }else{
    form.val('manual_draw_form',{'s_address':point.point.lng+','+point.point.lat})
  }
};

// 根据选择绘制路线的类型，展示相应面板
var draw_line_kind;
var select_draw_kind=function(kind){
  
  form.render()
  reset_efence()
  document.getElementById("handle_data_form").reset();
  transfer.reload('binded_dev', {
                  data: device
                  ,value:[]
                  ,title: ['未绑定', '绑定']
                  ,height:320
                  ,width:280
                  ,showSearch: true
                  ,parseData: function(res){
                    return {
                      "value": res.device_id //数据值
                      ,"title": '名称：'+res.user_name+'    ID:'+ res.device_id //数据标题
                      ,"disabled": res.disabled  //是否禁用
                      ,"checked": '' //是否选中
                    }
                  }
  })

  var show_panle=$('#nav_query_form')
  var show_title='导航路线查询'
  // 导航路线
  if(kind=='nav'){
    document.getElementById("nav_query_form").reset();
  }else if(kind=='trail'){
    document.getElementById("trail_query_form").reset();
    var show_panle=$('#trail_query_form')
    var show_title='轨迹路线查询'
  }else if(kind=='manual'){
    document.getElementById("manual_draw_form").reset();
    var show_panle=$('#manual_draw_form')
    var show_title='手动绘制路线'
    map.addEventListener('click', manual_draw_line);
    layer.msg('请点击地图进行路线绘制')
  }
  layer.open({
            type: 1
            ,title:show_title
            // ,area:['350px','300px']
            ,offset:'r'  
            // ,closeBtn:0
            ,id: 'line_query_form' //防止重复弹出
            ,shade: 0 //不显示遮罩
            ,content:show_panle
            ,cancel:function(index,lay){
              reset_efence()
            }
            ,success:function(){
              draw_line_kind=kind
            }
          })
}



form.on('submit(nav_query)',function(obj){
  
  var param=obj.field
  var transit = new BMap.DrivingRoute(map, {
    renderOptions: {
      map:map,
      enableDragging :true //起终点可进行拖拽
    },  
    onPolylinesSet:get_nav_point,
    // onSearchComplete:nav_result
  });
  // var s_address=$('#s_address').val(),e_address=$('#e_address').val();
  setTimeout(function(){transit.search(param.s_address,param.e_address);},200)
  return false

})

var handle_trail=function(pts){
  console.log(pts)
  var tarckpoint=new Array();
  var trackinfo=new Array();

  if(pts.length==0){
    layer.msg('该时间段没有轨迹数据');
    return false;
  };
  // 清除之前的覆盖物
  map.clearOverlays()
  //轨迹点封装

  for(var i=0;i<pts.length;i++){
    var point_len=pts.length
    var point_order=(Math.round((1/point_len)*100))*i+'%'
    var lng=pts[i]['lng']
    var lat=pts[i]['lat']
    
    var pt_trail = new BMap.Point(lng,lat);

    tarckpoint.push(pt_trail);
    trackinfo.push(pts[i]);
  };

  start_Icon = new BMap.Icon("/static/img/start.png", new BMap.Size(100,60),{anchor : new BMap.Size(20, 42),imageSize:new BMap.Size(40,40)});
  end_Icon = new BMap.Icon("/static/img/end.png", new BMap.Size(100,60),{anchor : new BMap.Size(20, 42),imageSize:new BMap.Size(40,40)});
  var endpoint=new BMap.Point(tarckpoint[tarckpoint.length-1].lng,tarckpoint[tarckpoint.length-1].lat);
  var startpoint=new BMap.Point(tarckpoint[0].lng,tarckpoint[0].lat);
  var startmarker = new BMap.Marker(startpoint,{icon:start_Icon});
  var endmarker=new BMap.Marker(endpoint,{icon:end_Icon});
  startmarker.setTitle('start');
  endmarker.setTitle('end');
  map.addOverlay(startmarker); 
  map.addOverlay(endmarker); 
  draw_line_bdmap(tarckpoint)
  map.setViewport(tarckpoint);

  form.val('handle_data_form',{'content':JSON.stringify(tarckpoint)})
}


// 历史轨迹查询画线
form.on('submit(trail_query)',function(obj){
  var trail_param=obj.field
  trail_param.map_kind='bd'
  base_info=JSON.stringify(trail_param)
  console.log(trail_param)
  post_info_ajax(trail_param,'trail','get_trail',handle_trail,'not close')
   return false
});



//添加选择设备列表
fill_raido_func(device,'tml_list','user_name','device_id')


//穿梭框渲染
var efence_bind_dev=transfer.render({
  elem: '#efence_bind_dev'
  ,id:'binded_dev'
  ,data: device
  ,title: ['未绑定', '绑定']
  ,height:320
  ,showSearch: true
  ,parseData: function(res){
    return {
      "value": res.device_id //数据值
      ,"title": '名称：'+res.user_name+'ID:'+ res.device_id//数据标题
      ,"disabled": res.disabled  //是否禁用
      ,"checked": '' //是否选中
    }
  }
})

// 时间框渲染
laydate.render({
  elem: '#s_time'
  ,type: 'datetime'
  // ,value:new Date(new Date(new Date().toLocaleDateString()).getTime())
  ,btns: ['clear','now', 'confirm']
});

laydate.render({
  elem: '#e_time'
  ,type: 'datetime'
  // ,value:new Date()
  ,btns: ['clear','now', 'confirm']
});


laydate.render({
  elem: '#s_trail'
  ,type: 'datetime'
  ,value:new Date(new Date(new Date().toLocaleDateString()).getTime())
  ,btns: ['clear','now', 'confirm']
});

laydate.render({
  elem: '#e_trail'
  ,type: 'datetime'
  ,value:new Date()
  ,btns: ['clear','now', 'confirm']
});


//时间范围
laydate.render({
  elem: '#effect_time'
  ,type: 'time'
  ,range: true
  ,format: 'HH:mm'
});


</script>
